/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package me.zhengjie.suli.check.repository;

import me.zhengjie.suli.check.domain.CheckDetail;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;

import java.util.List;

/**
 * @author Allen Gao
 * @website https://eladmin.vip
 * @date 2023-04-23
 **/
public interface CheckDetailRepository extends JpaRepository<CheckDetail, String>, JpaSpecificationExecutor<CheckDetail> {

    @Query(value = "select * from check_detail where check_id = ?1 ", nativeQuery = true)
    List<CheckDetail> getCheckDetailsByCheckId(String id);

    @Query(value = "select * from check_detail where check_detail_code = ?1 ", nativeQuery = true)
    CheckDetail getCheckDetailByCheckDetailCode(String checkDetailCode);

    @Query(value = "select top(1) * from check_detail where tray_code = ?1 ORDER BY create_time DESC ", nativeQuery = true)
    CheckDetail getCheckDetailByTrayCode(String trayCode);

    @Query(value = "select * from check_detail where material_code = ?1 and serial_number = ?2 and check_time is null ", nativeQuery = true)
    CheckDetail getCheckDetailByMaterialCodeAndSerialNumber(String materialCode, String serialNumber);

    @Query(value = "select check_detail.* from check_detail, checks, tray where check_detail.material_code = ?1 and check_detail.lot_code = ?2 and check_detail.check_id = checks.id and tray.tray_name = ?3 and tray.tray_code = checks.tray_code and checks.status = 2", nativeQuery = true)
    CheckDetail getCheckDetailByMaterialCodeAndLotCodeAndTrayName(String materialCode, String lotCode, String trayName);

    @Query(value = "select check_detail.* from check_detail, checks, tray where check_detail.material_code = ?1 and check_detail.check_id = checks.id and tray.tray_name = ?2 and tray.tray_code = checks.tray_code and checks.status = 2", nativeQuery = true)
    CheckDetail getCheckDetailByMaterialCodeAndTrayName(String materialCode, String trayName);


    /** 根据barrelId 桶ID 查找盘点明细 */
    @Query(value = "select top(1) check_detail.* from check_detail, checks where check_detail.check_id = checks.id and barrel_id = ?1 and checks.status = 2", nativeQuery = true)
    CheckDetail getCheckDetailByBarrelId(String barrelId);
}